/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.meducated.sandbox.scriptingandqueues;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceAware;

/**
 *
 * @author Carina
 */
@PersistenceAware
public class DemoStartPatientTask {

    public static String getCode() {

        PersistenceManager pm = PMF.get().getPersistenceManager();

        if (pm == null) {
            return "// Enter your code...";
        } else {
            DemoPatient pt = null;
            // Retrieve the demo patient
            try {
                pt = pm.getObjectById(DemoPatient.class, "DemoPatient");
            } catch (JDOObjectNotFoundException e) {
            }
            pm.close();

            if (pt == null) {
                return "// Enter your code...";
            } else {
                return pt.getCode();
            }
        }
    }

    public static void start(String code, boolean restart) {
        PersistenceManager pm = PMF.get().getPersistenceManager();

        DemoPatient pt = null;
        try {
            // Retrieve the demo patient
            pt = pm.getObjectById(DemoPatient.class, "DemoPatient");
        } catch (JDOObjectNotFoundException e) {
        }
        if (pt == null) {
            // Create the patient
            pt = new DemoPatient();
            pt.setHr(0);
            pt.setBp(new DemoPatient.BP());
            pt.getBp().setSbp(0);
            pt.getBp().setDbp(0);
            pt.setClock(0);

        }
        // Create the key of the patient
        String key = KeyFactory.createKeyString(DemoPatient.class.getSimpleName(),
                "DemoPatient");

        pt.setKey(key);

        pt.setCode(code);
        if (restart) {
            pt.setClock(0);
        }
        try {
        // Persist the demo patientey);
        pm.makePersistentAll(pt);
        }
        finally {
        pm.close();
        }

        // Start the patient task        
        Queue queue = QueueFactory.getQueue("demo-patient-queue");

        queue.add(TaskOptions.Builder.withUrl("/demopatienttask").param("key", "DemoPatient"));
    }
}
